//
//  EPMSQLTool.m
//  WeiBoByOC
//
//  Created by 马继鵬 on 17/4/13.
//  Copyright © 2017年 7TH. All rights reserved.
//

#import "EPMSQLTool.h"
#import <FMDatabaseQueue.h>

static NSString* dbName = @"home,db";
@interface EPMSQLTool()

@end

@implementation EPMSQLTool

+ (instancetype)sheardTool{
    static EPMSQLTool* tool;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [EPMSQLTool new];
        
    });
    return tool;
}

- (instancetype)init{
    if(self = [super init])
    {
        NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:dbName];
         self.queue = [FMDatabaseQueue databaseQueueWithPath:path];
        ///创建数据表格
        [self creatTable];
    }
    return self;
}

- (void)creatTable{
    NSString* filePath = [[NSBundle mainBundle]pathForResource:@"db.sql" ofType:nil];
    //准备SQL语句
    NSString* SQLStr = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    //执行SQL语句
    [self.queue inDatabase:^(FMDatabase *db) {
        if ([db executeStatements:SQLStr]){
            NSLog(@"创建成功");
        }else{
            NSLog(@"创建失败");
        }
    }];
}

#pragma
#pragma-查询字典

- (NSArray*)selectDataWithSQL:(NSString*)sql {
    NSMutableArray* temp = [NSMutableArray new];
    //执行SQL语句
    [[EPMSQLTool sheardTool].queue inDatabase:^(FMDatabase *db) {
        
        FMResultSet * reasultSet = [db executeQuery:sql withArgumentsInArray:nil];
        
        while (reasultSet.next) {
            NSMutableDictionary* dict = [NSMutableDictionary new];
            for (int i = 0; i < reasultSet.columnCount; i ++){
                NSString* key = [reasultSet columnNameForIndex:i];
                id value = [reasultSet objectForColumnIndex:i];
                dict[key] = value;
            }
            [temp addObject:dict];
        }
    }];
    
    return temp;
    
    
    return temp;
}


@end
